"""
System-related resources for FastMCP
"""

from fastmcp import FastMCP, Context
import psutil
import time
import json
from datetime import datetime


class SystemResources:
    """System monitoring and status resources for FastMCP."""

    def __init__(self, mcp: FastMCP):
        self.mcp = mcp

    async def get_system_status(self, ctx: Context) -> dict:
        """Get current system status and health information."""
        try:
            await ctx.info("Gathering system status information")

            # Get CPU usage
            cpu_percent = psutil.cpu_percent(interval=1)

            # Get memory usage
            memory = psutil.virtual_memory()

            # Get disk usage for current drive
            disk = psutil.disk_usage("/")

            return {
                "timestamp": datetime.now().isoformat(),
                "status": "healthy",
                "cpu": {
                    "usage_percent": cpu_percent,
                    "cores": psutil.cpu_count(),
                    "cores_physical": psutil.cpu_count(logical=False),
                },
                "memory": {
                    "total_gb": round(memory.total / (1024**3), 2),
                    "available_gb": round(memory.available / (1024**3), 2),
                    "used_gb": round(memory.used / (1024**3), 2),
                    "usage_percent": memory.percent,
                },
                "disk": {
                    "total_gb": round(disk.total / (1024**3), 2),
                    "free_gb": round(disk.free / (1024**3), 2),
                    "used_gb": round(disk.used / (1024**3), 2),
                    "usage_percent": round((disk.used / disk.total) * 100, 2),
                },
            }
        except ImportError:
            # Fallback if psutil is not available
            return {
                "timestamp": datetime.now().isoformat(),
                "status": "limited",
                "message": "System monitoring unavailable (psutil not installed)",
                "basic_info": {"uptime": "unknown", "python_memory": "unknown"},
            }
        except Exception as e:
            await ctx.error(f"Error gathering system status: {str(e)}")
            return {
                "timestamp": datetime.now().isoformat(),
                "status": "error",
                "error": str(e),
            }

    def get_running_processes(self) -> dict:
        """Get information about running processes."""
        try:
            processes = []
            for proc in psutil.process_iter(
                ["pid", "name", "cpu_percent", "memory_percent"]
            ):
                try:
                    proc_info = proc.info
                    if (
                        proc_info["cpu_percent"] is not None
                        and proc_info["cpu_percent"] > 0
                    ):
                        processes.append(proc_info)
                except (psutil.NoSuchProcess, psutil.AccessDenied):
                    continue

            # Sort by CPU usage
            processes.sort(key=lambda x: x["cpu_percent"] or 0, reverse=True)

            return {
                "timestamp": datetime.now().isoformat(),
                "total_processes": len(psutil.pids()),
                "active_processes": len(processes),
                "top_processes": processes[:10],  # Top 10 by CPU usage
            }
        except ImportError:
            return {
                "timestamp": datetime.now().isoformat(),
                "error": "Process monitoring unavailable (psutil not installed)",
            }

    def get_system_uptime(self) -> dict:
        """Get system uptime information."""
        try:
            boot_time = psutil.boot_time()
            uptime_seconds = time.time() - boot_time

            # Convert to human readable format
            days = int(uptime_seconds // 86400)
            hours = int((uptime_seconds % 86400) // 3600)
            minutes = int((uptime_seconds % 3600) // 60)

            return {
                "boot_time": datetime.fromtimestamp(boot_time).isoformat(),
                "uptime_seconds": int(uptime_seconds),
                "uptime_formatted": f"{days}d {hours}h {minutes}m",
                "current_time": datetime.now().isoformat(),
            }
        except ImportError:
            return {
                "error": "Uptime information unavailable (psutil not installed)",
                "current_time": datetime.now().isoformat(),
            }

    def get_network_info(self) -> dict:
        """Get network interface information."""
        try:
            interfaces = {}

            # Get network interface statistics
            net_io = psutil.net_io_counters(pernic=True)
            net_addrs = psutil.net_if_addrs()

            for interface, addrs in net_addrs.items():
                interface_info = {
                    "addresses": [],
                    "statistics": net_io.get(interface, {}),
                }

                for addr in addrs:
                    addr_info = {
                        "family": str(addr.family),
                        "address": addr.address,
                        "netmask": addr.netmask,
                        "broadcast": addr.broadcast,
                    }
                    interface_info["addresses"].append(addr_info)

                # Convert statistics to dict if available
                if interface in net_io:
                    stats = net_io[interface]
                    interface_info["statistics"] = {
                        "bytes_sent": stats.bytes_sent,
                        "bytes_recv": stats.bytes_recv,
                        "packets_sent": stats.packets_sent,
                        "packets_recv": stats.packets_recv,
                    }

                interfaces[interface] = interface_info

            return {
                "timestamp": datetime.now().isoformat(),
                "interfaces": interfaces,
                "interface_count": len(interfaces),
            }
        except ImportError:
            return {
                "error": "Network information unavailable (psutil not installed)",
                "timestamp": datetime.now().isoformat(),
            }

    def register(self):
        """Register all system resources with FastMCP."""
        self.mcp.resource(
            uri="system://status",
            name="System Status",
            description="Current system status and health information",
            mime_type="application/json",
            tags={"system", "monitoring", "health"},
        )(self.get_system_status)

        self.mcp.resource(
            uri="system://processes",
            name="Running Processes",
            description="Information about currently running processes",
            mime_type="application/json",
            tags={"system", "processes", "monitoring"},
        )(self.get_running_processes)

        self.mcp.resource(
            uri="system://uptime",
            name="System Uptime",
            description="System uptime and boot information",
            mime_type="application/json",
            tags={"system", "uptime", "boot"},
        )(self.get_system_uptime)

        self.mcp.resource(
            uri="system://network",
            name="Network Information",
            description="Network interfaces and statistics",
            mime_type="application/json",
            tags={"system", "network", "interfaces"},
        )(self.get_network_info)
